import React, { useState, useCallback } from 'react';
import { Form, Input, Button } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline, LockOutline, UserOutline, CheckOutline, CloseOutline } from 'antd-mobile-icons';
import './index.less';
import { udp } from '@cscec/udp-mobile-ui';
import BoldOutlined from '@ant-design/icons/lib/icons/BoldOutlined';
import opacityImage from '../../assets/images/opacity.jpg';

interface LoginForm {
  studentId: string;
  password: string;
}



export default function EconomicIndex() {
const [loading, setLoading] = useState(false);

  const [form] = Form.useForm();
  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState({
    studentId: false,
    password: false
  });
  const [toastVisible, setToastVisible] = useState(false);
  const [toastConfig, setToastConfig] = useState({
    message: '',
    isSuccess: true
  });
  // 显示Toast提示
  const showToast = useCallback((message: string, isSuccess: boolean = true) => {
    setToastConfig({ message, isSuccess });
    setToastVisible(true);
    setTimeout(() => {
      setToastVisible(false);
    }, 3000);
  }, []);

  // 切换密码显示状态
  const togglePasswordVisibility = useCallback(() => {
    setShowPassword(prev => !prev);
  }, []);

  // 处理表单提交
  const handleSubmit = useCallback(async (values: LoginForm) => {
    setLoading(true);
    // 模拟API调用延迟
    const { studentId, password } = values;
      const { code, data } = await udp.request.body({
      url: '/api/user/login',
      headers: { 'Content-Type': 'application/json', 'cache-control': 'no-cache' },
      data: {
        userName: studentId,
        password:udp.CryptoJS.encode(password)//加密保存
      }
    });
    
    if (code == 200) {
      showToast('登录成功！即将进入学习中心~', true);
          data.user.accessToken = data.userToken;
          udp.setUser(data.user);
          localStorage.setItem('__login__', data.userToken);
          localStorage.setItem('__login_info__', JSON.stringify(data.user));
          udp.open('/BellaEnglish');
    } else {
      showToast('学号或密码不正确，请重新输入~', false);
      form.setFieldValue('password', '');
      setLoading(false);
    }
  }, [form, showToast]);

  // 处理表单验证失败
  const handleFinishFailed = useCallback(({ errorFields }: any) => {
    const newErrors = {
      studentId: false,
      password: false
    };
    
    errorFields.forEach((field: any) => {
      if (field.name[0] === 'studentId') newErrors.studentId = true;
      if (field.name[0] === 'password') newErrors.password = true;
    });
    
    setErrors(newErrors);
  }, []);

    const handleRegister = () => {
      udp.open('/ParentRegister');
    };


return (
      <div className="login-page">
      {/* 装饰元素 */}
      <div className="decoration dot-1"></div>
      <div className="decoration dot-2"></div>
      <div className="decoration dot-3"></div>
      
      {/* 主内容区域 */}
      <div className="login-container">
        {/* 品牌区域 */}
        <div className="brand-section">
          <div className="logo float">
            {/* <BoldOutlined className="logo-icon" /> */}
            <img src={opacityImage}
             className="logo-icon" 
             style={{
              width:'100%',
              height:"100%",
              borderRadius:"50%"
            }} alt=""/>
          </div>
          <h1 className="brand-title">贝拉英语</h1>
          <p className="brand-subtitle">快乐学英语，轻松成长</p>
        </div>
        
        {/* 登录表单区域 */}
        <div className="login-form-section">
          <h2 className="form-title">登录学习账号</h2>
          
          <Form
            form={form}
            onFinish={handleSubmit}
            onFinishFailed={handleFinishFailed}
            className="login-form"
          >
            {/* 学号输入 */}
            <Form.Item
              name="studentId"
              //rules={[{ required: true, message: '请填写学号哦~' }]}
               rules={[{ required: true, message: '请填写用户名哦~' }]}
              className={`form-item ${errors.studentId ? 'error' : ''}`}
            >
              <div className="input-container">
                <UserOutline className="input-icon" />
                <Input
                  placeholder="请输入您的用户名"
                  className="login-input"
                  onFocus={() => setErrors(prev => ({ ...prev, studentId: false }))}
                />
              </div>
            </Form.Item>
            
            {/* 密码输入 */}
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请填写密码哦~' }]}
              className={`form-item ${errors.password ? 'error' : ''}`}
            >
              <div className="input-container">
                <LockOutline className="input-icon" />
                <Input
                  type={showPassword ? 'text' : 'password'}
                  placeholder="请输入您的密码"
                  className="login-input"
                  onFocus={() => setErrors(prev => ({ ...prev, password: false }))}
                />
                <button
                  type="button"
                  className="password-toggle"
                  onClick={togglePasswordVisibility}
                >
                  {showPassword ? <EyeOutline /> : <EyeInvisibleOutline />}
                </button>
              </div>
            </Form.Item>
            
            {/* 登录按钮 */}
            <Button
              type="submit"
              loading={loading}
              className={`login-button ${loading ? '' : 'pulse'}`}
            >
              {loading ? '登录中...' : '登录学习'}
            </Button>
          </Form>
          
          {/* 注册提示 */}
          {/* <div className="register-tip">
            <p className="tip-text">还没有账号？</p>
            <p className="contact-text">请联系教务老师注册</p>
          </div> */}
          
          {/* 家长注册账号按钮 */}
          <Button
            onClick={handleRegister}
            loading={loading}
            style={{
              marginTop:'16px',
              width:'100%',
              height:'48px',
              backgroundColor:'rgba(30,183,216,0.1)',
              color:'#1EB7D8',
              fontWeight:'bold',
              borderRadius:'16px',
              border:'2px solid rgba(30, 183, 216, 0.2)',
              fontSize:'16px',
              transition:'background-color 0.3s',
              animation:'pulse 3s infinite'
            }}
          >
            {loading ? '跳转中...' : '家长注册账号'}
          </Button>
        </div>
        
        {/* 底部提示 */}
        <div className="footer-tip">
          <p className="tip-content">
            每天坚持学习15分钟，英语进步更明显哦！
          </p>
        </div>
      </div>
      
      {/* 自定义Toast */}
      <div className={`custom-toast ${toastVisible ? 'show' : ''}`}>
        <div className={`toast-icon ${toastConfig.isSuccess ? 'success' : 'error'}`}>
          {toastConfig.isSuccess ? <CheckOutline /> : <CloseOutline />}
        </div>
        <p className="toast-message">{toastConfig.message}</p>
      </div>
    </div> 
)
}